
package jpoco.android;

import net.oauth.OAuthProblemException;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;

public abstract class AbstractActivity extends Activity 
{
	
    protected void openWebBrowser(String url)
    {
    	Log.i(this.getClass().getName(), "about to launch browser, url: " + url);
    	Intent i = new Intent(Intent.ACTION_VIEW);
    	i.setData(Uri.parse(url));
    	startActivity(i);
    }
    
    protected void startThread(String name, Runnable r)
    {
    	Thread t = new Thread(r);
    	t.setName(name);
    	t.start();
    }
    
    protected void startThread(Runnable r)
    {
    	String name = this.getClass().getName() + " thread";
    	startThread(name, r);
    }
    
    protected void onFail(Throwable t)
    {
		Throwable cause = (t.getCause() == null) ? t : t.getCause();
		
    	Log.e(this.getClass().getName(), t.getMessage(), t);
    	
    	final StringBuilder msg = new StringBuilder();
    	
    	msg.append("Fail: ");
    	
    	if (cause.getMessage() != null)
    	{
    		msg.append(cause.getMessage() + " | ");
    	}
    	
    	msg.append(cause.getClass().getName());
    	
    	if (cause instanceof OAuthProblemException)
    	{
    		OAuthProblemException oauthFail = (OAuthProblemException) cause;
    		
    		if (oauthFail.getProblem() != null)
    		{
    			Log.e(this.getClass().getName(), "OAuth problem: " + oauthFail.getProblem());
 
    			msg.append("\n" + oauthFail.getProblem());
    		}
    		
    		for (String key : oauthFail.getParameters().keySet())
    		{
    			msg.append("\n" + key + "=" + oauthFail.getParameters().get(key));
    		}
    	}

    	Runnable showAlert = new Runnable()
    	{
    		
    		public void run()
    		{
				final AlertDialog alert = new AlertDialog.Builder(AbstractActivity.this).create();
				alert.setMessage(msg);
				alert.setButton("OK", new DialogInterface.OnClickListener()
				{
		
					public void onClick(DialogInterface dialog, int whichButton)
					{
						alert.dismiss();
					}
				});
				alert.show();
    		}
    	};
    	
    	this.runOnUiThread(showAlert);
    	
    }
    
}
